package com.zjq.authoritysystem.utils;

import com.zjq.authoritysystem.entity.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author BetOnMe
 * @version 1.0
 * @ClassName RoleTreeUtil
 * @description: TODO
 * @since 2023年10月15日 20:42:56
 */
@Slf4j
public class PermissionTreeUtil {

    /**
     * 生成菜单权限树形结构数据
     *
     * @param permissionList 菜单权限信息
     * @param parentId       父级编号
     * @return 菜单权限树
     */
    public static List<Permission> makeRolesTree(List<Permission> permissionList, Integer parentId) {
        List<Permission> permissions = new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream()
                .filter(permission -> permission != null && permission.getParentId() == parentId)
                .forEach(item -> {
                    Permission permission = new Permission();
                    BeanUtils.copyProperties(item, permission);
                    List<Permission> children = makeRolesTree(permissionList, permission.getId());
                    if (children.size() > 0) {
                        permission.setChildren(children);
                    }
                    permissions.add(permission);
                });
        return permissions;
    }
}
